<template>
  <div class="order-list-container">
    <!-- 订单状态筛选 -->
    <div class="order-tabs">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部订单" name="-1"></el-tab-pane>
        <el-tab-pane label="待付款" name="0"></el-tab-pane>
        <el-tab-pane label="待发货" name="1"></el-tab-pane>
        <el-tab-pane label="待收货" name="2"></el-tab-pane>
        <el-tab-pane label="已完成" name="3"></el-tab-pane>
        <el-tab-pane label="已取消" name="4"></el-tab-pane>
      </el-tabs>
    </div>

    <!-- 订单列表 -->
    <div class="order-list">
      <el-card v-for="order in orderList" :key="order.id" class="order-item">
        <div class="order-header">
          <div class="order-info">
            <span class="order-no">订单号：{{ order.orderNo }}</span>
            <span class="order-time">下单时间：{{ formatDate(order.createdTime) }}</span>
          </div>
          <div class="order-status" :class="'status-' + order.status">
            {{ getStatusText(order.status) }}
          </div>
        </div>

        <div class="order-content">
          <div class="order-details">
            <div class="amount-info">
              <div class="amount-item">
                <span>商品总额：</span>
                <span class="price">¥{{ order.totalAmount }}</span>
              </div>
              <div class="amount-item">
                <span>运费：</span>
                <span class="price">¥{{ order.freightAmount }}</span>
              </div>
              <div class="amount-item total">
                <span>实付金额：</span>
                <span class="price highlight">¥{{ order.payAmount }}</span>
              </div>
            </div>
          </div>

          <div class="order-actions">
            <!-- 待付款状态 -->
            <template v-if="order.status === 0">
              <el-button type="primary" size="small" @click="handlePay(order)">立即付款</el-button>
              <el-button size="small" @click="handleCancel(order)">取消订单</el-button>
            </template>
            
            <!-- 待发货状态 -->
            <template v-if="order.status === 1">
              <el-button size="small" @click="handleRemind(order)">提醒发货</el-button>
            </template>
            
            <!-- 待收货状态 -->
            <template v-if="order.status === 2">
              <el-button type="primary" size="small" @click="handleConfirmReceive(order)">确认收货</el-button>
              <el-button size="small" @click="handleViewLogistics(order)">查看物流</el-button>
            </template>
            
            <!-- 已完成状态 -->
            <template v-if="order.status === 3">
              <el-button size="small" @click="handleViewLogistics(order)">查看物流</el-button>
              <el-button size="small" @click="handleDelete(order)">删除订单</el-button>
            </template>
          </div>
        </div>
      </el-card>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'OrderList',
  data() {
    return {
      activeTab: '-1',
      orderList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false
    }
  },
  created() {
    this.loadOrders()
  },
  methods: {
    async loadOrders() {
      try {
        this.loading = true
        const params = {
          page: this.currentPage,
          size: this.pageSize
        }
        
        // 如果不是全部订单，添加状态筛选
        if (this.activeTab !== '-1') {
          params.status = parseInt(this.activeTab)
        }

        const response = await this.request.get('/orders/list', { params })
        this.orderList = response.data
        this.total = response.total || response.data.length
      } catch (error) {
        console.error('加载订单失败:', error)
        this.$message.error('加载订单失败，请重试')
      } finally {
        this.loading = false
      }
    },

    handleTabClick() {
      this.currentPage = 1
      this.loadOrders()
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.loadOrders()
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.loadOrders()
    },

    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
    },

    getStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '待发货',
        2: '待收货',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知状态'
    },

    async handlePay(order) {
      // 跳转到支付页面
      this.$router.push({
        path: '/payment',
        query: {
          orderNo: order.orderNo,
          amount: order.payAmount
        }
      })
    },

    async handleCancel() {
      try {
        await this.$confirm('确定要取消该订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // const response = await this.request.post('/orders/cancel', {
        //   orderNo: order.orderNo
        // })
        
        this.$message.success('订单已取消')
        this.loadOrders()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消订单失败:', error)
          this.$message.error('取消订单失败，请重试')
        }
      }
    },

    // handleRemind(order) {
    //   this.$message.success('已通知商家尽快发货')
    // },

    async handleConfirmReceive() {
      try {
        await this.$confirm('确认已收到商品？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // const response = await this.request.post('/orders/confirm', {
        //   orderNo: order.orderNo
        // })
        
        this.$message.success('确认收货成功')
        this.loadOrders()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('确认收货失败:', error)
          this.$message.error('确认收货失败，请重试')
        }
      }
    },

    handleViewLogistics(order) {
      // 跳转到物流详情页面
      this.$router.push(`/logistics/${order.orderNo}`)
    },

    async handleDelete() {
      try {
        await this.$confirm('确定要删除该订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // const response = await this.request.post('/orders/delete', {
        //   orderNo: order.orderNo
        // })
        
        this.$message.success('订单已删除')
        this.loadOrders()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除订单失败:', error)
          this.$message.error('删除订单失败，请重试')
        }
      }
    }
  }
}
</script>

<style scoped>
.order-list-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.order-tabs {
  background: #fff;
  padding: 0 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.order-item {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.order-info {
  display: flex;
  gap: 20px;
  color: #666;
}

.order-no {
  font-weight: bold;
}

.order-status {
  font-weight: bold;
}

.status-0 { color: #E6A23C; }
.status-1 { color: #409EFF; }
.status-2 { color: #67C23A; }
.status-3 { color: #909399; }
.status-4 { color: #F56C6C; }

.order-content {
  padding: 15px 0;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.amount-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.amount-item {
  display: flex;
  gap: 10px;
  color: #666;
}

.price {
  color: #333;
  font-weight: bold;
}

.price.highlight {
  color: #F56C6C;
  font-size: 1.2em;
}

.order-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  text-align: right;
  margin-top: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .order-content {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }

  .order-actions {
    justify-content: flex-end;
  }

  .order-info {
    flex-direction: column;
    gap: 5px;
  }
}
</style> 